/**
 * Copyright (C) 2018-2021
 * All rights reserved, Designed By www.yixiang.co

 */
package gat.common.util;

import com.alibaba.fastjson.JSON;
import com.bitsun.core.common.constant.HeaderConstants;
import com.bitsun.core.common.constant.RuntimeContext;
import com.bitsun.core.common.constant.RuntimeContextHolder;
import com.bitsun.core.common.exception.AppException;
import com.bitsun.core.common.web.CurrentUser;
import org.springframework.util.StringUtils;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;
import java.util.Objects;

/**
 * 获取 HttpServletRequest
 * @author Zheng Jie
 * @date 2018-11-24
 */
public class RequestHolder {

    public static HttpServletRequest getHttpServletRequest() {
        return ((ServletRequestAttributes) Objects.requireNonNull(RequestContextHolder.getRequestAttributes())).getRequest();
    }

    public static CurrentUser initUser(HttpServletRequest request){
        String token = request.getHeader(HeaderConstants.token);
        CurrentUser user = null;
        if (!StringUtils.isEmpty(token)){
            try {
                String verifyToken = JwtUtil.verifyToken(token);
                user = JSON.parseObject(verifyToken, CurrentUser.class);
                RuntimeContext context = new RuntimeContext();
                context.setRequest(request);
                context.setCurrentUser(user);
                RuntimeContextHolder.setCurrentRuntimeContext(context);
            }catch (Exception e) {
                throw new AppException("登录信息已过期", "000001");
            }
        }
        return user;
    }

    public static String getDomain(){
        String domain = getHttpServletRequest().getHeader(HeaderConstants.domain);
        if (!StringUtils.isEmpty(domain)){
            domain = domain.replace("https://", "").replace("http://","");
        }
        return domain;
    }
}
